﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using KillBill.Business.Entities;
using KillBill.Business.Modules.Administration;
using KillBill.Common.Security;
using KillBill.Services.DTO;
using KillBill.Services.Modules.Administration.IServices;

namespace KillBill.Services.Modules.Administration
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class SecurityService : ISecurityService
    {
        private SecurityManager _securityManager;
        private ActiveSessions _activeSessions = new ActiveSessions();
        public SecurityService()
        {
            _securityManager = new SecurityManager();
        }
        #region ISecurityService Members
        public ActiveSessions GetSessions()
        {
            return _activeSessions;
        }
        public Session LogIn(string id, string password)
        {
            Employee employee = _securityManager.LogIn(id, password);
            Session outDTO = new Session();
            if (employee.Success)
            {
                outDTO.Employee = employee;
                outDTO.Messages = employee.Messages;
                //Register User in Global Session Cache
                _activeSessions.StartSession(outDTO);
                outDTO.Success = true;
            }
            else
            {
                outDTO.Messages = employee.Messages;
                outDTO.Success = false;
            }
            return outDTO;
        }
        public void LogOut(string sessionId)
        {
            _activeSessions.CloseSession(sessionId);
        }
        public KillBillDTO IsAuthorized(string sessionId, string[] validRoles)
        {
            Session session = GetSessions().GetSession(sessionId);
            KillBillDTO outDTO = new KillBillDTO();
            outDTO.Success = true;
            if (session == null)
            {
                outDTO.Success = false;
                outDTO.Messages = new List<string>();
                outDTO.Messages.Add("La sesión no es valida o ha caducado... Reinicie el programa");
                return outDTO;
            }
            bool Allow = false;
            
            foreach (string validRole in validRoles)
            {
                if (session.Employee.EmployeeRoleID == validRole)
                    Allow = true;
            }

            outDTO.Success = Allow;
            
            if (Allow == false)
            {
                outDTO.Messages = new List<string>();
                outDTO.Messages.Add("El usuario actual no esta autorizado para realizar la transacción...");
            }
            return outDTO;
        }
        #endregion
    }
}
